<?php


namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\TransformApi;
use common\models\Address;
use common\models\Goods;
use common\models\GoodsClassify;
use common\models\GoodsSpec;
use common\models\Order;
use common\models\OrderComment;
use common\models\System;
use common\models\User;
use Yii;

class GoodsController extends BaseController
{
    /**
     * 获取分类
     * @return array
     */
    public function actionClassify()
    {
        $data = GoodsClassify::find()
            ->where(['status'=>1])
            ->select(['id as classify_id','name'])
            ->orderBy(['sort'=>SORT_DESC])
            ->asArray()->all();
        return commonApi::message('成功',true,$data);
    }
    /**
     * 列表
     * @return array
     */
    public function actionList()
    {
        $page = (int)Yii::$app->request->get('page',1);
        $keyword = Yii::$app->request->get('keyword','');
        $classify_id = Yii::$app->request->get('classify_id','');
        $query = Goods::find()
            ->select(['id as g_id','main_img','name','price','sales_volume','feature'])
            ->where(['status'=>1,'delete'=>0])
            ->orderBy(['sort'=>SORT_DESC,'create_time'=>SORT_DESC]);
        if ($keyword){
            $query->andWhere(['like','name',$keyword]);
        }
        if ($classify_id){
            $query->andWhere(['classify_id'=>$classify_id]);
        }
        $data = PageApi::apiPage($query,$page);
        foreach ($data['data'] as &$datum){
            $datum['feature'] = explode(',',$datum['feature']);
            $datum['main_img'] = commonApi::getDomain($datum['main_img']);
        }
        return commonApi::message('成功',true,$data);
    }

    /**
     * 详情
     * @return array
     */
    public function actionDetails()
    {
        $userid = self::$userid;
        $g_id = (int)Yii::$app->request->get('g_id','');
        if (!$g_id){
            return commonApi::message('请选择商品！',false);
        }
        $goods = Goods::find()->where(['id'=>$g_id,'status'=>1,'delete'=>0])->one();
        if (!$goods){
            return commonApi::message('商品不存在',false);
        }
        $info = $goods->toArray();
        $img = explode(',',$info['img']);
        $imgArr = [];
        foreach ($img as $value){
            $value = commonApi::getDomain($value);
            $imgArr[] = ['img'=>$value];
        }
        $shop_discount = System::getModel()->shop_discount??0;
        $huiyuan = false;
        if ($shop_discount>0){
            $huiyuan = (new User())->isHuiyuan($userid,'','',0);
            if ($huiyuan){
                $info['price'] = $info['price']*($shop_discount/10);
                $info['price'] = TransformApi::decimalPoint($info['price']);
            }
        }
        $spec = (new GoodsSpec())->getSpec($g_id,$huiyuan,$shop_discount);
        $data = [
            'g_id'=>$g_id,
            'name'=>$info['name'],
            'img'=>$imgArr,
            'price'=>$info['price'],
            'sales_volume'=>$info['sales_volume']??0,
            'details'=>$info['details'],
            'spec'=>$spec,
        ];
        return commonApi::message('成功',true,$data);
    }

    /**
     * 计算
     * @return array
     */
    public function actionCalculate()
    {
        $post = Yii::$app->request->post();
        $g_id = (int)$post['g_id']??'';
        $spec_id = (int)$post['spec_id']??'';
        $num = (int)$post['num']??0;
        if (!$g_id){
            return commonApi::message('请选择商品！',false);
        }
        if (!$spec_id){
            return commonApi::message('请选择规格！',false);
        }
        if ($num<=0){
            return commonApi::message('数量必须大于0',false);
        }
        $data = (new Order())->calculate([['g_id'=>$g_id,'spec_id'=>$spec_id,'num'=>$num]],self::$userid);
        if (!$data['success']){
            return $data;
        }
        return commonApi::message('成功',true,$data['data']['goods_data']);
    }

    /**
     * 下单
     * @return array
     */
    public function actionBuy()
    {
        $post = Yii::$app->request->post();
        $g_id = (int)$post['g_id']??'';
        $spec_id = (int)$post['spec_id']??'';
        $num = (int)$post['num']??0;
        $address_id = $post['address_id'] ?? '';
        $userid = self::$userid;
        if (!$g_id){
            return commonApi::message('请选择商品！',false);
        }
        if (!$spec_id){
            return commonApi::message('请选择规格！',false);
        }
        if ($num<=0){
            return commonApi::message('数量必须大于0',false);
        }
        if (!$address_id){
            return commonApi::message('请选择收货地址！',false);
        }
        $address = Address::find()->where(['id'=>$address_id,'userid'=>$userid])->asArray()->one();
        if (!$address){
            return commonApi::message('地址不存在',false);
        }
        $order = new Order();
        $data = $order->calculate([['g_id'=>$g_id,'spec_id'=>$spec_id,'num'=>$num]],$userid);
        if (!$data['success']){
            return $data;
        }
        //微信订单号
        $party_order = Order::makePartyOrder();
        //系统订单号
        $order_sn = Order::makeOrderid();
        $desc = '购买商品-'.$order_sn;
        $pay = $order->getPayresponse($data['data']['goods_data']['pay_amount'],$userid,$party_order,$desc);
        if (!$pay['success']){
            return $pay;
        }
        $saveRes = $order->saveOrder($pay['data'],$data['data'],$userid,$order_sn,$party_order,$address);
        if (!$saveRes['success']){
            return $saveRes;
        }
        return commonApi::message($saveRes['msg'],true,$pay['data']);
    }

    /**
     * 获取评论
     * @return array
     */
    public function actionGetComment()
    {
        $g_id = Yii::$app->request->get('g_id','');
        $page = Yii::$app->request->get('page',1);
        $query = OrderComment::find()
            ->where(['good_id'=>$g_id,'status'=>1])
            ->select(['userid','content','imgs','logistics_star','service_attitude','create_time'])
            ->orderBy(['create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $userid = array_unique(array_column($data['data'],'userid'));
        $user = User::find()->where(['id'=>$userid])->select(['id','info'])->asArray()->all();
        $user = array_column($user,'info','id');
        foreach ($data['data'] as &$datum){
            $info = empty($user[$datum['userid']])?[]:json_decode($user[$datum['userid']],true);
            $datum['nickname'] = $info['nickName']??'';
            $datum['headimgurl'] = $info['avatarUrl']??'';
            $datum['create_time'] = date('Y.m.d H:i',strtotime($datum['create_time']));
            $imgs = explode(',',$datum['imgs']);
            foreach ($imgs as &$img){
                $img = commonApi::getDomain($img);
            }
            $datum['imgs'] = array_filter($imgs);
        }
        return commonApi::message('ok',true,$data);
    }
}